<template>
    <div>
        <el-row class="row-with-margin">
            <el-col :span="24">
                <div>
                    <!-- 顶部按钮组 -->
                    <el-button-group>
                        <el-button @click="combinedOrder">合单</el-button>
                        <el-button @click="batchCancelOrder">批量取消订单</el-button>
                        <el-button>导入</el-button>
                        <el-button @click="exportExcel">导出</el-button>
                    </el-button-group>
                </div>
            </el-col>
        </el-row>

        <el-row class="row-with-margin">
            <el-col :span="24">
                <div>
                    订单状态：
                    <el-select clearable placeholder="请选择订单状态" v-model="param.orderStatus">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                    始发地：
                    <el-cascader :options="originOptions" :props="props" clearable placeholder="请选择始发地"
                        v-model="param.dpaAddress3"></el-cascader>
                    目的地：
                    <el-cascader :options="originOptions" :props="props" clearable placeholder="请选择目的地"
                        v-model="param.cdaAddress3"></el-cascader>
                </div>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
                <el-form :inline="true">
                    <el-form-item label="下单时间">
                        <el-date-picker type="daterange" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" v-model="param.betweenTime">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="收货信息" label-width="100px">
                        <el-input placeholder="请输入关键词搜索" style="width: 200px; margin-left: 10px;"
                            v-model="param.customerAddress">
                        </el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="queryBtn">查询</el-button>
                        <el-button style="margin-left: 10px;" @click="resetForm">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <el-row style="margin-top: 0px;margin-bottom: 0px;">
            <el-col :span="24">
                <div>
                    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                        <el-tab-pane label="客户订单" name="first"></el-tab-pane>
                        <!-- <el-tab-pane label="用户订单" name="second"></el-tab-pane> -->
                    </el-tabs>
                </div>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
                <div>
                    <el-table :data="tableData" style="width: 100%; margin-top: 10px; padding-top: 0px;"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="id" label="订单号" width="180">
                            <template slot-scope="scope">
                                <el-link type="primary" @click="queryOrderDetail(scope.row)">
                                    {{ scope.row.id }}
                                </el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="waybillId" label="关联运单号" width="180"></el-table-column>
                        <el-table-column label="始发地" width="180">
                            <template v-slot="scope">
                                <div>
                                    <span>{{ scope.row.dpaProvince }}</span>/
                                    <span>{{ scope.row.dpaCity }}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="目的地" width="180">
                            <template v-slot="scope">
                                <div>
                                    <span>{{ scope.row.cdaProvince }}</span>/
                                    <span>{{ scope.row.cdaCity }}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="客(用)户名称" width="180"></el-table-column>
                        <el-table-column label="订单状态" width="180">
                            <template v-slot="scope">
                                <span :style="{ color: getColor(scope.row.orderStatus) }">
                                    <span v-if="scope.row.orderStatus == 0">待分配</span>
                                    <span v-else-if="scope.row.orderStatus == 1">待调度</span>
                                    <span v-else-if="scope.row.orderStatus == 2">运输中</span>
                                    <span v-else-if="scope.row.orderStatus == 3">已签收</span>
                                    <span v-else-if="scope.row.orderStatus == 4">已拒绝</span>
                                    <span v-else-if="scope.row.orderStatus == 5">已取消</span>
                                    <span v-else-if="scope.row.orderStatus == 6">待提货</span>
                                    <span v-else>未知状态</span>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="faHuoAddress" label="发货信息" width="180"></el-table-column>
                        <el-table-column prop="customerAddress" label="收货信息" width="180"></el-table-column>
                        <el-table-column prop="expectedShipmentTime" label="预计发货时间" width="180"></el-table-column>
                        <el-table-column prop="expectedDeliveryTime" label="预计收货时间" width="180"></el-table-column>
                        <el-table-column label="订单类型" width="180">
                            <template v-slot="scope">
                                <span v-if="scope.row.orderType == 0">整车</span>
                                <span v-else-if="scope.row.orderType == 1">零担</span>
                                <span v-else>未知类型</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="货物类型" width="180">
                            <template v-slot="scope">
                                <span v-if="scope.row.goodsType == 0">日用品</span>
                                <span v-else-if="scope.row.goodsType == 1">食品</span>
                                <span v-else-if="scope.row.goodsType == 2">文件</span>
                                <span v-else-if="scope.row.goodsType == 3">家具</span>
                                <span v-else-if="scope.row.goodsType == 4">其他</span>
                                <span v-else>未知类型</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="goodsCount" label="货物数量" width="180"></el-table-column>
                        <el-table-column prop="allVolume" label="总体积" width="180"></el-table-column>
                        <el-table-column prop="allWeight" label="总重量" width="180"></el-table-column>
                        <el-table-column prop="totalFee" label="运费合计" width="180"></el-table-column>
                        <el-table-column prop="remarks" label="订单备注" width="180"></el-table-column>
                        <el-table-column prop="orderCreatedTime" label="下单时间" width="180"></el-table-column>
                        <el-table-column prop="realName" label="创建人" width="180"></el-table-column>
                        <el-table-column prop="employeeId" label="创建人" width="180" v-if="false"> </el-table-column>
                        <el-table-column label="操作" width="250">
                            <template slot-scope="scope">
                                <el-button type="text" size="medium" @click="scheduling(scope.row)"
                                    :disabled="scope.row.orderStatus == 5 || scope.row.waybillId !== null && scope.row.waybillId !== ''">调度</el-button>
                                <el-button type="text" size="medium" @click="queryOrderDetail(scope.row)">详情</el-button>
                                <el-button type="text" size="medium"
                                    :disabled="scope.row.employeeId == 0 || scope.row.waybillId !== null"
                                    @click="splitOrder(scope.row)">拆单</el-button>
                                <el-button type="text" size="medium" :disabled="scope.row.orderStatus != 1"
                                    @click="cancelOrder(scope.row)">取消订单</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
                <el-pagination background :page-sizes="[1,5, 10, 20, 30, 50]" :page-size="pageSize"
                    :current-page="pageNum" :total="total" layout="total,sizes,prev, pager, next,jumper"
                    @next-click="nextPage" @prev-click="prevPage" @current-change="changePage"
                    @size-change="sizeChange">
                </el-pagination>
            </el-col>
        </el-row>
    </div>
</template>

<script>
export default {
    data() {
        return {
            activeTab: 'first',
            pageSize: 5,
            pageNum: 1,
            total: 0,
            // tab:'',
            tableData: [],//表格对象
            multipleSelection: [],
            param: {},//参数对象
            options: [{ value: '0', label: '待分配' },
            { value: '1', label: '待调度' },
            { value: '2', label: '运输中' },
            { value: '3', label: '已签收' },
            { value: '4', label: '已拒绝' },
            { value: '5', label: '已取消' },
            { value: '6', label: '待提货' },], //订单状态下拉框
            value: '',//订单状态下拉框赋值
            originOptions: [],//复制张晨曦的
            props: { value: 'id', label: 'name', children: 'cityList' },  //配置级联选择器多选  还是复制张晨曦的
        }
    },

    methods: {
        nextPage(val) {//当前页
            //下一页

            if (this.activeTab == 'first') {
                this.pageNum = val
                // 客户订单标签页被点击
                this.handleCustomerOrderTabClick();
            }
        },
        prevPage(val) {//当前页
            //上一页

            if (this.activeTab == 'first') {
                this.pageNum = val
                // 客户订单标签页被点击
                this.handleCustomerOrderTabClick();
            }
        },
        changePage(val) {
            //跳转页

            if (this.activeTab == 'first') {
                this.pageNum = val
                // 客户订单标签页被点击
                this.handleCustomerOrderTabClick();
            }
        },
        sizeChange(val) {
            //改变每页条数

            if (this.activeTab == 'first') {
                this.pageNum = 1
                this.pageSize = val
                // 客户订单标签页被点击
                this.handleCustomerOrderTabClick();
            }
        },
        // ---------------------------------------------分页方法分割线------------------------------------------------------------------------
        getColor(status) {
            switch (status) {
                case '0':
                    return 'orange';
                case '1':
                    return 'yellow';
                case '2':
                    return 'blue';
                case '3':
                    return 'green';
                case '4':
                    return 'red';
                case '5':
                    return 'grey';
                default:
                    return 'black';
            }
        },
        handleSelectionChange(val) {//点击批量删除复选框调用此方法
            this.multipleSelection = val
        },
        handleTabClick(tab) {
            if (tab.name === 'first') {
                this.tab = 'first'
                // 客户订单标签页被点击
                this.handleCustomerOrderTabClick();
            } else if (tab.name === 'second') {
                // 用户订单标签页被点击
                this.handleUserOrderTabClick();
            }
        },
        handleCustomerOrderTabClick() {
            // 处理客户订单标签页的点击事件
            console.log('客户订单标签页被点击');//查询全部客户订单
            let pageParam = {};
            pageParam.pageNum = this.pageNum;
            pageParam.pageSize = this.pageSize;
            pageParam.param = this.param;
            this.$axios.post('api/order/queryCustomerOrder', pageParam)
                .then(resp => {
                    console.log(resp.data);
                    if (resp.data.code === 200) {
                        this.tableData = resp.data.data.list
                        this.total = resp.data.data.total
                        this.loading = false
                    }

                })
                .catch(error => {
                    console.error('操作失败:', error);
                    this.$message.error('网络请求失败，请稍后再试');
                });
        },
        handleUserOrderTabClick() {
            // 处理用户订单标签页的点击事件
            console.log('用户订单标签页被点击');
            let pageParam = {};
            pageParam.pageNum = this.pageNum;
            pageParam.pageSize = this.pageSize;
            pageParam.param = this.param;
            this.$axios.post('api/order/queryUserOrder', pageParam)
                .then(resp => {
                    console.log(resp.data);
                    if (resp.data.code === 200) {
                        this.tableData = resp.data.data.list
                        this.total = resp.data.data.total
                    }
                })
                .catch(error => {
                    console.error('操作失败:', error);
                    this.$message.error('网络请求失败，请稍后再试');
                });
        },
        queryOrigin() {
            //查询所有始发地  复制张晨曦的
            this.$axios.get("/api/provincial/queryProvincial")
                .then(resp => {
                    console.log(resp.data)
                    if (resp.data.code == 200) {
                        this.originOptions = resp.data.data
                    }
                })
        },
        queryBtn() {
            this.pageNum = 1
            if (this.activeTab == 'first') {
                this.handleCustomerOrderTabClick()
            }
            if (this.activeTab == 'second') {
                this.handleUserOrderTabClick()
            }
        },
        resetForm() { //重置按钮调用方法
            this.param = { orderStatus: '', dpaAddress3: [], cdaAddress3: [], betweenTime: [], customerAddress: '' }
            if (this.activeTab == 'first') {
                this.handleCustomerOrderTabClick()
            }
            if (this.activeTab == 'second') {
                this.handleUserOrderTabClick()
            }
        },
        queryOrderDetail(val) {
            if (val.orderSource == 1) {
                this.$router.push({ path: '/orderDetail', query: { 'orderId': val.id } })
            }
            if (val.orderSource == 0) {
                this.$router.push({ path: '/userOrderDetail', query: { 'orderId': val.id } })
            }

        },
        scheduling(val) {
            this.$confirm('是否确认进行订单调度', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //点击确定再发送请求
                this.$axios.post("/api/order/scheduling", val)
                    .then(resp => {
                        console.log(resp.data)
                        if (resp.data.code === 200) {
                            this.$message({
                                message: '调度成功!!!!',
                                type: 'success'
                            });
                            window.location.reload();
                        }
                    })
                    .catch(error => {
                        console.error('操作失败:', error);
                        this.$message.error('网络请求失败，请稍后再试');
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        combinedOrder() {
            this.$confirm('是否确认要合并选中订单', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //点击确定再发送请求
                this.$axios.post("/api/order/combinedOrder", this.multipleSelection)
                    .then(resp => {
                        console.log(this.multipleSelection);
                        if (resp.data.code === 200) {
                            window.location.reload();
                            this.$message({
                                message: '合单成功!!!!',
                                type: 'success'
                            });

                        }
                        if (resp.data.code === 2009) {
                            this.$message({
                                message: '仅有相同用户的订单可进行合单操作',
                                type: 'error'
                            });
                        }
                        if (resp.data.code === 2010) {
                            this.$message({
                                message: '选择的订单已关联运单',
                                type: 'error'
                            });
                        }
                        if (resp.data.code === 2011) {
                            this.$message({
                                message: '选择的订单始发地不同，无法合单',
                                type: 'error'
                            });
                        }
                        if (resp.data.code === 2012) {
                            this.$message({
                                message: '选择的订单目的地或收货地址不同，无法合单',
                                type: 'error'
                            });
                        }

                    })
                    .catch(error => {
                        console.error('操作失败:', error);
                        this.$message.error('网络请求失败，请稍后再试');
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        splitOrder(val) {
            this.$confirm('是否确认要取消合单', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //点击确定再发送请求
                this.$axios.post("/api/order/splitOrder", val)
                    .then(resp => {
                        console.log(this.multipleSelection);
                        if (resp.data.code === 200) {
                            window.location.reload();
                            this.$message({
                                message: '拆单成功!!!!',
                                type: 'success'
                            });

                        }
                    })
                    .catch(error => {
                        console.error('操作失败:', error);
                        this.$message.error('网络请求失败，请稍后再试');
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        cancelOrder(val) {
            this.$confirm('是否确认要取消订单', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //点击确定再发送请求
                this.$axios.post("/api/order/cancelOrder", val)
                    .then(resp => {
                        console.log(this.multipleSelection);
                        if (resp.data.code === 200) {
                            window.location.reload();
                            this.$message({
                                message: '订单取消成功!!!!',
                                type: 'success'
                            });

                        }
                    })
                    .catch(error => {
                        console.error('操作失败:', error);
                        this.$message.error('网络请求失败，请稍后再试');
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        batchCancelOrder() {
            this.$confirm('是否确认要取消选中订单', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //点击确定再发送请求
                this.$axios.post("/api/order/batchCancelOrder", this.multipleSelection)
                    .then(resp => {
                        console.log(this.multipleSelection);
                        if (resp.data.code === 200) {
                            window.location.reload();
                            this.$message({
                                message: '订单取消成功!!!!',
                                type: 'success'
                            });
                        }
                        if (resp.data.code === 500) {
                            window.location.reload();
                            this.$message({
                                message: '选中的订单已关联运单号，请取消调度后进行操作',
                                type: 'error'
                            });
                        }
                    })
                    .catch(error => {
                        console.error('操作失败:', error);
                        this.$message.error('网络请求失败，请稍后再试');
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        exportExcel() {

            // 使用 axios 获取文件流
            this.$axios({
                url: 'api/order/export',
                method: 'GET',
                responseType: 'blob',  // 指定响应类型为 blob
            }).then(response => {
                // 创建 Blob 对象
                const blob = response.data;

                // 创建一个 URL 对象来表示该 Blob
                const url = window.URL.createObjectURL(blob);

                // 创建一个临时的下载链接
                const link = document.createElement('a');
                link.href = url;
                link.download = 'data.xlsx';  // 设置下载的文件名

                // 触发点击事件下载文件
                document.body.appendChild(link);
                link.click();

                // 下载后清理链接
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url); // 释放 Blob URL
            }).catch(error => {
                console.error('导出失败:', error);
            });
        },

    },
    created() {
        this.handleCustomerOrderTabClick(),
            this.queryOrigin()
    }
}
</script>

<style scoped>
.row-with-margin {
    margin-bottom: 20px;
    /* 根据需要调整间隙大小 */
}
</style>